﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using MvcGMaps.Models;
using MvcGMaps.ViewModels;
using MvcGMaps.DAL;
using PagedList;
using BotDetect.Web.UI.Mvc;
using System.Web.Security;


namespace MvcGMaps.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        protected UnitOfWork uow = new UnitOfWork();

        [AllowAnonymous]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [AllowAnonymous]
        public ActionResult New(decimal lat, decimal lng)
        {
            ViewBag.TypeDDL = new SelectList(uow.MarkerTypeRepo.Get(), "TypeID", "TypeName", 1);

            return PartialView("NewModal", new Marker(lat, lng));
        }
        
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        [CaptchaValidation("CaptchaCode", "MarkerCaptcha", "Your input doesn't match displayed characters!")]
        public JsonResult New(Marker marker)
        {
            ViewModels.Response response = new ViewModels.Response();

            if (!ModelState.IsValid)
            {
                // TODO: Captcha validation failed, show error message
                response.IsSuccess = false;
                response.Message = "Неправильный код CAPTCHA!";
            }
            else
            {
                try
                {
                    uow.MarkerRepository.Insert(marker);
                    uow.Save();

                    response.Message = "Запись добавлена";
                    MvcCaptcha.ResetCaptcha("MarkerCaptcha");
                }
                catch (Exception ex)
                {
                    response.IsSuccess = false;
                    response.Message = ex.Message;
                }
            }

            return Json(response);
        }

        [HttpGet]
        [AllowAnonymous]
        public ActionResult Edit(int markerId)
        {
            Marker marker = uow.MarkerRepository.GetByID(markerId);
            
            if (marker != null)
            {
                ViewBag.TypeDDL = new SelectList(uow.MarkerTypeRepo.Get(), "TypeID", "TypeName", marker.TypeID);
                ViewBag.StatusDDL = new SelectList(uow.StatusRepo.Get(), "StatusID", "StatusName", marker.StatusID);
            }

            return PartialView("EditModal", marker);
        }
        
        [HttpPost]
        [Authorize]
        [ValidateAntiForgeryToken]
        public JsonResult Edit(Marker marker)
        {
            ViewModels.Response response = new ViewModels.Response();
            
            if (ModelState.IsValid)
            {
                try
                {
                    uow.MarkerRepository.Update(marker);
                    uow.Save();

                    response.Message = "Запись обновлена";
                }
                catch (Exception ex)
                {
                    response.IsSuccess = false;
                    response.Message = ex.Message;
                }
            }
            else
            {
                response.IsSuccess = false;
                response.Message = "У вас что-то не то с моделью...";
            }

            return Json(response);
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult Search(SearchModel searchModel)
        {
            var localModel = searchModel ?? new SearchModel();
            
            int pageSize = 3;
            int pageNumber = (localModel.Page ?? 1);

            var markers = uow.MarkerRepository.Get(localModel).ToPagedList(pageNumber, pageSize);

            return PartialView("Search", markers);
        }

        [HttpGet]
        [AllowAnonymous]
        public JsonResult GetMarkers()
        {
            var result = uow.MarkerRepository.GetJsonMarkers().ToList();
            return Json(new { IsSuccess = true, Markers = result }, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        [AllowAnonymous]
        public ActionResult OpenLogin()
        {
            return PartialView("LoginDialog");
        }

        [HttpGet]
        [Authorize]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            ViewData["Logoff"] = true;
            return PartialView("LoginButton");
        }

        [AllowAnonymous]
        public ActionResult GetLoginButton()
        {
            return PartialView("LoginButton");
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public JsonResult Login(UserModel model)
        {
            if (ModelState.IsValid)
            {
                User user = uow.UserRepo.Get(model);
                if (user != null)
                {
                    FormsAuthentication.SetAuthCookie(user.Username, true);
                    return Json(new { IsSuccess = true });
                }

            }
            ModelState.AddModelError("", "Неправильное имя пользователя или пароль.");
            return Json(new { IsSuccess = false });
        }

        protected override void Dispose(bool disposing)
        {
            uow.Dispose();
            base.Dispose(disposing);
        }
    }
}
